from django.conf import settings
from django.db.models import Avg, Sum, Count, Max, Min, Q, F
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.filters import SearchFilter, OrderingFilter
import json
from iClouds.Permissions import (
    OR,
    AllPermissions,
    MyPermissions,
    BoxPermissions,
    WeChatPermissions,
    BarPermissions,
)
from iClouds.Authentication import (
    MyJWTAuthentication,
    BoxJWTAuthentication,
    WeChatJWTAuthentication,
    BarJWTAuthentication,
)

# from iClouds.serializers import TestSerializer
from iClouds.apidev import filter_views, has_Random

from .reconf import webAttr, Receipt, semsConf, mailConf, settlConf, paysConf, alertConf
from .FilterBackends import *
from .serializers import *
from .models import *

from . import redis as REDIS
from . import sems as SEMS

import re


# http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']


class AllinpaySemsMsgViewSet(viewsets.ModelViewSet):
    __title__ = "发送短信请求"
    __doc__ = """
    create:\n
    <h4>发送短信请求</h4>\n
        返回短信序列号
    `发送间隔请设置大于60秒`
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = SemsMsgSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 验证用户
        # try:
        #     phone = AllinpayUserList.objects.get(
        #         Q(phone=serializer.data["username"])
        #         | Q(email=serializer.data["username"])
        #         | Q(openid=serializer.data["username"])
        #     )
        # except BaseException as err:
        #     raise serializers.ValidationError({"username": "用户不存在"})
        username = serializer.data["username"]
        # 获取消息体
        code, quen, timeout = has_Random(4), has_Random(3), 3
        # 缓存消息
        REDIS.redis_put("sems", username, {"code": code, "quen": quen}, timeout * 60)
        # 发送消息
        if serializer.data["act"] == "SEMS":
            # username = phone.phone
            if not username:
                raise serializers.ValidationError({"username": "用户未绑定手机"})
            is_send = SEMS.Send_Sems_Sdk(
                {"phone": username, "code": code, "quen": quen, "timeout": timeout}
            )
            if not is_send:
                serializers.ValidationError({"username": "发送短信失败"})
        elif serializer.data["act"] == "EMAIL":
            # username = phone.email
            if not username:
                raise serializers.ValidationError({"username": "用户未绑定邮箱"})
            raise serializers.ValidationError({"username": "暂未开通该功能"})
        else:
            raise serializers.ValidationError({"username": "验证方式错误"})
        return Response({"rescode": 200, "resmsg": "消息序列号:" + quen})


class AllinpaySemsVerifViewSet(viewsets.ModelViewSet):
    __title__ = "验证短信求"
    __doc__ = """
    create:\n
    <h4>验证短信求</h4>\n
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = SemsVerifSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # # 验证用户
        # try:
        #     phone = AllinpayUserList.objects.get(
        #         Q(phone=serializer.data["username"])
        #         | Q(email=serializer.data["username"])
        #         | Q(openid=serializer.data["username"])
        #     )
        # except BaseException as err:
        #     raise serializers.ValidationError({"username": "用户名不能匹配"})
        username = serializer.data["username"]
        # 验证短信
        sems = serializer.data["password"]
        if not settings.DEBUG:
            code = REDIS.redis_get("sems", username, "code")
            if not code or not sems == code:
                raise serializers.ValidationError({"password": "验证码不能匹配"})
        # 清除短信缓存
        REDIS.redis_del("sems", username)
        return Response({"rescode": 200, "resmsg": "验证通过"})


class AllinpaySysAttrViewSet(viewsets.ModelViewSet):
    __title__ = "查询网站属性"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>查询网站属性设置信息</h4>

    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        data = webAttr()
        serializer = AllinpaySysAttrSerializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySysAttrSetViewSet(viewsets.ModelViewSet):
    __title__ = "修改网站属性"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>修改网站属性设置信息</h4>

    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpaySysAttrSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = webAttr()
        data.up_json(serializer.data)
        # serializer = self.get_serializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySecretkeyListViewSet(viewsets.ModelViewSet):
    __title__ = "查询收单信息"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>查询收单设置信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        data = Receipt()
        serializer = AllinpaySecretkeyListSerializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySecretkeySetViewSet(viewsets.ModelViewSet):
    __title__ = "设置收单信息"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>查询收单设置信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpaySecretkeyListSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = Receipt()
        data.up_json(serializer.data)
        # serializer = self.get_serializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySysSemsViewSet(viewsets.ModelViewSet):
    __title__ = "查询短信网关"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>查询短信网关信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        data = semsConf()
        serializer = AllinpaySysSemsSerializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySysSemsSetViewSet(viewsets.ModelViewSet):
    __title__ = "设置短信网关"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>设置短信网关信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpaySysSemsSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = semsConf()
        data.up_json(serializer.data)
        # serializer = self.get_serializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySysMailViewSet(viewsets.ModelViewSet):
    __title__ = "查询邮件网关"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>查询邮件网关信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        data = mailConf()
        serializer = AllinpaySysMailSerializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySysMailSetViewSet(viewsets.ModelViewSet):
    __title__ = "设置邮件网关"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>设置邮件网关信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpaySysMailSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = mailConf()
        data.up_json(serializer.data)
        # serializer = self.get_serializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySysSettlViewSet(viewsets.ModelViewSet):
    __title__ = "查询结算设置"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>查询结算设置信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        data = settlConf()
        serializer = AllinpaySysSumSerializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySysSettlSetViewSet(viewsets.ModelViewSet):
    __title__ = "修改结算设置"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>修改结算设置信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpaySysSumSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = settlConf()
        data.up_json(serializer.data)
        # serializer = self.get_serializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayAlertViewSet(viewsets.ModelViewSet):
    __title__ = "查询语音设置"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>查询语音设置信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        data = alertConf()
        serializer = AllinpayAlertSerializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayAlertSetViewSet(viewsets.ModelViewSet):
    __title__ = "修改语音设置"
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>修改语音设置信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayAlertSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = alertConf()
        data.up_json(serializer.data)
        # serializer = self.get_serializer(data.to_json())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayWeChatSetViewSet(viewsets.ModelViewSet):
    __title__ = "微信接口参数设置"
    __group__ = "后台配置"
    __info__ = {"get": "查询微信接口参数设置", "post": "编辑微信接口参数设置"}
    __doc__ = """
    list:\n
    <h4>查询微信接口参数设置</h4>
    retrieve:\n
    <h4>停用</h4>
    create:\n
    <h4>编辑微信接口参数设置</h4>
    """
    http_method_names = ["get", "post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayWeChatSerializer
    queryset = None

    def list(self, request, *args, **kwargs):
        try:
            with open(settings.CONF / "wechat.json", "r") as fs:
                code = fs.read()
                dictcode = json.loads(code)
        except BaseException as err:
            raise serializers.ValidationError({"attr": "微信接口参数未配置"})
        return Response({"rescode": 200, "resmsg": dictcode})

    def retrieve(self, request, *args, **kwargs):
        raise serializers.ValidationError({"disable": "该接口已禁用"})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 写入配置文件
        jsoncode = json.dumps(serializer.data)
        with open(settings.CONF / "wechat.json", "w") as fs:
            fs.write(jsoncode)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPulsarSetViewSet(viewsets.ModelViewSet):
    __title__ = "消息队列参数设置"
    __group__ = "后台配置"
    __info__ = {"get": "查询消息队列参数设置", "post": "编辑消息队列参数设置"}
    __doc__ = """
    list:\n
    <h4>查询消息队列参数设置</h4>
    retrieve:\n
    <h4>查询消息队列服务器命名空间</h4>
    create:\n
    <h4>编辑消息队列参数设置</h4>
    """
    http_method_names = ["get", "post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayPlsarSerializer
    queryset = None

    def list(self, request, *args, **kwargs):
        try:
            with open(settings.CONF / "pulsar.json", "r") as fs:
                code = fs.read()
                dictcode = json.loads(code)
        except BaseException as err:
            raise serializers.ValidationError({"attr": "消息队列参数未配置"})
        return Response({"rescode": 200, "resmsg": dictcode})

    def retrieve(self, request, *args, **kwargs):
        try:
            with open(settings.CONF / "pulsar.json", "r") as fs:
                code = fs.read()
                dictcode = json.loads(code)
        except BaseException as err:
            raise serializers.ValidationError({"attr": "消息队列参数未配置"})

        import requests

        try:
            r = requests.request(
                method="get", url="http://pulsardb:8080/admin/v2/namespaces/public"
            )

            if r.status_code == 200:
                x = r.json()
            else:
                x = ""
        except BaseException as err:
            x = None
        return Response(
            {
                "rescode": 200,
                "resmsg": x,
            }
        )

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 写入配置文件
        jsoncode = json.dumps(serializer.data)
        with open(settings.CONF / "pulsar.json", "w") as fs:
            fs.write(jsoncode)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPulsarTopicViews(viewsets.ModelViewSet):
    __title__ = "消息队列查询订阅主题信息"
    __doc__ = """
    create:\n
    <h4>消息队列查询订阅主题信息</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpayPulsarTopicSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        import requests

        try:
            r = requests.request(
                method="get",
                url=f'http://pulsardb:8080/admin/v2/persistent/public/{serializer.get("namespaces")}/{serializer.get("topic")}/stats',
            )
            if r.status_code == 200:
                x = r.json()
            else:
                x = ""
        except BaseException as err:
            x = None
        return Response(
            {
                "rescode": 200,
                "resmsg": x,
            }
        )


class HasVersionBarViews(viewsets.ModelViewSet):
    __title__ = "场所端版本"
    __doc__ = """
    create:\n
    <h4>场所端最新ROM版本</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        import os, re

        vers, web = [], []
        #  "/opt/statics/download/"
        for root, dirs, files in os.walk(settings.MEDIA_ROMS, topdown=True):
            for name in files:
                if name.startswith("BarManager.") and name.endswith(".tar.gz"):
                    # v = re.search(r"^BarManager\.(\d*?)\.tar\.gz$", name).group(1)
                    # vers.append(v)
                    vers.append(name)
                if name.startswith("WebPackage.") and name.endswith(".tar.gz"):
                    # v = re.search(r"^BarManager\.(\d*?)\.tar\.gz$", name).group(1)
                    # vers.append(v)
                    web.append(name)
        # 列表排序
        vers.sort(reverse=True)
        web.sort(reverse=True)
        return Response({"rescode": 200, "resmsg": {"API": vers, "WEB": web}})


class HasVersionYunViews(viewsets.ModelViewSet):
    __title__ = "云端版本"
    __doc__ = """
    create:\n
    <h4>云端当前版本</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        x = self.readConf()
        c = self.readConfIDC()
        l = self.readUpdateLog()
        return Response({"rescode": 200, "resmsg": {"ROM": x, "IDC": c}, "logs": l})

    def readConf(self):
        try:
            with open(settings.VERFILES, "r") as fs:
                ver = fs.readline()
                return ver
        except BaseException as err:
            return ""

    def readConfIDC(self):
        try:
            with open(settings.CONF / "idc.json", "r") as fs:
                idc = json.loads(fs.read())
                return idc
        except BaseException as err:
            return ""

    def readUpdateLog(self):
        try:
            with open(settings.UPDATE_LOG, "r") as fs:
                ver = fs.readlines()
                return ver
        except BaseException as err:
            return ""


class UpdateImagesViews(viewsets.ModelViewSet):
    __title__ = "上传图片"
    __doc__ = """
    create:\n
    <h4>上传图片文件</h4>
        "Content-Type":"multipart/form-data"
    """
    http_method_names = ["post"]
    parser_classes = [MultiPartParser, FormParser]
    # authentication_classes = []
    # permission_classes = [AllPermissions]
    authentication_classes = [MyJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [MyPermissions | WeChatPermissions]
    serializer_class = UpdateImagesSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()

        images = request.FILES
        if len(images) == 1:
            try:
                for f in images.getlist("files"):
                    if f.size > 5120000:
                        raise serializers.ValidationError({"detail": "图片尺寸超出限制，<5M"})
                    excdname = os.path.splitext(f.name)[1]
                    allname = has_Random(12) + excdname
                    f._set_name(allname)
                    with open(settings.MEDIA_ROOT / f"{allname}", "wb") as fs:
                        for chunk in f.chunks():
                            fs.write(chunk)
                    return Response(
                        {
                            "rescode": 200,
                            "resmsg": {
                                "url": f"/static/upload/{allname}",
                                "types": f.content_type,
                                "type": serializer.data.get("type"),
                            },
                        }
                    )
            except Exception as err:
                raise serializers.ValidationError({"detail": err})
        else:
            raise serializers.ValidationError({"upload": "上传失败"})


class UpdatePackageViews(viewsets.ModelViewSet):
    __title__ = "上传场所系统包"
    __group__ = "后台配置"
    __doc__ = """
    list:\n
    <h4>固件文件列表</h4>
    retrieve:\n
    <h4>用户文件信息</h4>
        禁用
    create:\n
    <h4>上传场所系统包</h4>
        "Content-Type":"multipart/form-data"
    """
    http_method_names = ["get", "post"]
    parser_classes = [MultiPartParser, FormParser]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = UpdateFilesSerializer
    queryset = None

    def list(self, request, *args, **kwargs):
        import os, re

        vers = []
        for root, dirs, files in os.walk(settings.MEDIA_ROMS, topdown=True):
            for name in files:
                vers.append(settings.MEDIA_URL + name)

        return Response({"rescode": 200, "resmsg": vers})

    def retrieve(self, request, *args, **kwargs):
        raise serializers.ValidationError({"status": "该接口已停用"})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()

        images = request.FILES
        if len(images) == 1:
            try:
                for f in images.getlist("files"):
                    if f.size > 1024000000:
                        raise serializers.ValidationError({"detail": "文件尺寸超出限制，<5M"})

                    api = re.compile(r"^BarManager\.(\d*?)\.tar\.gz$")
                    web = re.compile(r"^WebPackage\.(\d*?)\.tar\.gz$")
                    a, w = api.match(f.name), web.match(f.name)
                    if not a and not w:
                        raise serializers.ValidationError({"detail": "上传不合法"})

                    with open(settings.MEDIA_ROMS / f"{f.name}", "wb") as fs:
                        for chunk in f.chunks():
                            fs.write(chunk)
                    return Response(
                        {
                            "rescode": 200,
                            "resmsg": {
                                "url": f"/static/download/{f.name}",
                                "types": f.content_type,
                                "type": serializer.data["type"],
                            },
                        }
                    )
            except Exception as err:
                raise serializers.ValidationError({"detail": err})
        else:
            raise serializers.ValidationError({"upload": "上传失败"})


class UpdateSoftViews(viewsets.ModelViewSet):
    __title__ = "用户文件地址"
    __group__ = "后台配置"
    __doc__ = """
    list:\n
    <h4>用户文件列表</h4>
    retrieve:\n
    <h4>用户文件信息</h4>
        禁用
    create:\n
    <h4>上传用户文件</h4>
        "Content-Type":"multipart/form-data"
    """
    http_method_names = ["get", "post"]
    parser_classes = [MultiPartParser, FormParser]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = UpdateSoftSerializer
    queryset = None

    def list(self, request, *args, **kwargs):
        import os, re

        vers = []
        for root, dirs, files in os.walk(settings.MEDIA_SOFT, topdown=True):
            for name in files:
                vers.append(settings.STATIC_URL + "soft/" + name)

        return Response({"rescode": 200, "resmsg": vers})

    def retrieve(self, request, *args, **kwargs):
        raise serializers.ValidationError({"status": "该接口已停用"})
        # instance = self.get_object()
        # serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": "该接口禁用"})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        images = request.FILES
        if len(images) == 1:
            try:
                for f in images.getlist("files"):
                    with open(settings.MEDIA_SOFT / f"{f.name}", "wb") as fs:
                        for chunk in f.chunks():
                            fs.write(chunk)
                    return Response(
                        {
                            "rescode": 200,
                            "resmsg": {
                                "url": f"/static/soft{f.name}",
                                "types": f.content_type,
                                "type": serializer.data["type"],
                            },
                        }
                    )
            except Exception as err:
                raise serializers.ValidationError({"detail": err})
        else:
            raise serializers.ValidationError({"upload": "上传失败"})


class GlobalConfAllTermViews(viewsets.ModelViewSet):
    __title__ = "全局经营名目"
    __info__ = {"post": "获取全局经营名目列表"}
    __group__ = "后台配置"
    __doc__ = """
    create:\n
    <h4>全局经营名目</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response({"rescode": 200, "resmsg": settings.ALL_TERMSN_ITEMS})


class GlobalConfIntegralListViews(viewsets.ModelViewSet):
    __title__ = "全局积分类型"
    __info__ = {
        "get": "全局积分类型列表或详情",
        "post": "全局积分类型创建",
        "put": "全局积分类型更新",
        "delete": "全局积分类型移除",
    }
    __group__ = "后台配置"
    __doc__ = """
    list:\n
    <h4>全局积分类型列表</h4>
    retrieve:\n
    <h4>全局积分类型详情</h4>
    create:\n
    <h4>全局积分类型创建</h4>
    update:\n
    <h4>全局积分类型更新</h4>
    delete:\n
    <h4>全局积分类型移除</h4>
    """
    http_method_names = ["get", "post", "put"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
        BarJWTAuthentication,
    ]
    permission_classes = [
        MyPermissions | BoxPermissions | WeChatPermissions | BarPermissions
    ]
    serializer_class = GlobalConfIntegralListSerializer
    queryset = AllinpayIntegralList.objects.all()
    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["status"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


# class GlobalWorkitemModelViews(viewsets.ModelViewSet):
#     __title__ = "全局工作项模板"
#     __info__ = {
#         "get": "全局工作项模板列表或详情",
#         "post": "全局工作项模板创建",
#         "put": "全局工作项模板更新",
#         "delete": "全局工作项模板移除",
#     }
#     __group__ = "后台配置"
#     __doc__ = """
#     list:\n
#     <h4>全局工作项模板列表</h4>
#     retrieve:\n
#     <h4>全局工作项模板详情</h4>
#     create:\n
#     <h4>全局工作项模板创建</h4>
#     update:\n
#     <h4>全局工作项模板更新</h4>
#     delete:\n
#     <h4>全局工作项模板移除</h4>
#     """
#     http_method_names = ["get", "post", "put"]
#     authentication_classes = [MyJWTAuthentication]
#     permission_classes = [MyPermissions]
#     serializer_class = GlobalWorkitemModelSerializer
#     queryset = AllinpayWorkitemModel.objects.all()

#     def list(self, request, *args, **kwargs):
#         queryset = self.filter_queryset(self.get_queryset())
#         serializer = self.get_serializer(queryset, many=True)
#         return Response({"rescode": 200, "resmsg": serializer.data})

#     def retrieve(self, request, *args, **kwargs):
#         instance = self.get_object()
#         serializer = self.get_serializer(instance)
#         return Response({"rescode": 200, "resmsg": serializer.data})

#     def create(self, request, *args, **kwargs):
#         serializer = self.serializer_class(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response({"rescode": 200, "resmsg": serializer.data})

#     def update(self, request, *args, **kwargs):
#         # 是否验证参数完整性 False:验证， True:不验证
#         partial = True
#         instance = self.get_object()
#         serializer = self.get_serializer(instance, data=request.data, partial=partial)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response({"rescode": 200, "resmsg": serializer.data})


# class DjangoCeleryBeatPeriodictaskViews(viewsets.ModelViewSet):
#     __title__ = "全局计划任务列表"
#     __info__ = {
#         "get": "全局计划任务列表或详情",
#     }
#     __group__ = "后台配置"
#     __doc__ = """
#     list:\n
#     <h4>全局工作项模板列表</h4>
#     retrieve:\n
#     <h4>全局工作项模板详情</h4>
#     """
#     http_method_names = ["get"]
#     # authentication_classes = [MyJWTAuthentication]
#     # permission_classes = [MyPermissions]
#     authentication_classes = []
#     permission_classes = [AllPermissions]
#     serializer_class = DjangoCeleryBeatPeriodictaskSerializer
#     queryset = DjangoCeleryBeatPeriodictask.objects.all()

#     def list(self, request, *args, **kwargs):
#         queryset = self.filter_queryset(self.get_queryset())
#         serializer = self.get_serializer(queryset, many=True)
#         return Response({"rescode": 200, "resmsg": serializer.data})

#     def retrieve(self, request, *args, **kwargs):
#         instance = self.get_object()
#         serializer = self.get_serializer(instance)
#         data = serializer.data.copy()
#         if data.get("crontab"):
#             data["info"] = DjangoCeleryBeatCrontabscheduleSerializer(
#                 DjangoCeleryBeatCrontabschedule.objects.filter(id=data.get("crontab")),
#                 many=True,
#             ).data
#         elif data.get("interval"):
#             data["info"] = DjangoCeleryBeatIntervalscheduleSerializer(
#                 DjangoCeleryBeatIntervalschedule.objects.filter(
#                     id=data.get("interval")
#                 ),
#                 many=True,
#             ).data
#         elif data.get("solar"):
#             data["info"] = DjangoCeleryBeatSolarscheduleSerializer(
#                 DjangoCeleryBeatSolarschedule.objects.filter(id=data.get("solar")),
#                 many=True,
#             ).data
#         elif data.get("clocked"):
#             data["info"] = DjangoCeleryBeatClockedscheduleSerializer(
#                 DjangoCeleryBeatClockedschedule.objects.filter(id=data.get("clocked")),
#                 many=True,
#             ).data
#         else:
#             data["info"] = None
#         return Response({"rescode": 200, "resmsg": data})


class CeleryTaskResViewSet(viewsets.ModelViewSet):
    __title__ = "查询异步任务结果"
    __group__ = "异步任务"
    __info__ = {"post": "查询异步任务结果"}
    __doc__ = """
    create:
    <h4>查询异步任务结果</h4>
        对于比较耗时的查询接口，将立即返回异步任务ID。
        通过异步任务轮询结果。
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    # authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication,WeChatJWTAuthentication]
    # permission_classes = [MyPermissions | BoxPermissions | WeChatPermissions]
    serializer_class = CeleryTaskResSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        cid = serializer.data.get("celeryID")
        res = REDIS.redis_key_get("celeryReses", f"celery-task-meta-{cid}")
        # x = json.loads(res)
        # print(x)
        return Response({"rescode": 200, "resmsg": res})


# class FileUploadViews(viewsets.ModelViewSet):
#     __title__ = "上传截图"
#     __doc__ = """
#     create:\n
#     <h4>上传图片文件</h4>
#         "Content-Type":"multipart/form-data"
#     """
#     http_method_names = ["post"]
#     parser_classes = [MultiPartParser, FormParser]
#     authentication_classes = []
#     permission_classes = [AllPermissions]
#     serializer_class = FileUploadSerializer
#     queryset = None

#     def create(self, request, *args, **kwargs):
#         serializer = self.serializer_class(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         # serializer.save()
#         print(len(request.FILES))
#         print(serializer.data)
#         images = request.FILES
#         for f in images.getlist("imageFile1"):
#             print(f.name)
#             with open(settings.MEDIA_JPEG / f"{f.name}", "wb") as fs:
#                 for chunk in f.chunks():
#                     fs.write(chunk)
#         return Response({"rescode": 200, "resmsg": "ok"})


class ShowRedisCacheDataViewSet(viewsets.ModelViewSet):
    __title__ = "查询缓存数据"
    __group__ = "后台配置"
    __info__ = {"get": "查询Redis缓存列表", "put": "清空缓存"}
    __doc__ = """
    list:
    <h4>查询缓存数据列表</h4>
    retrieve:
    <h4>查询缓存数据详情</h4>
    update:\n
    <h4>全局工作项模板更新</h4>    
    """
    http_method_names = ["get", "put"]
    authentication_classes = [
        MyJWTAuthentication,
    ]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def list(self, request, *args, **kwargs):
        # queryset = self.filter_queryset(self.get_queryset())
        # serializer = self.get_serializer(queryset, many=True)
        data = settings.CACHES.keys()
        # print(data)
        return Response({"rescode": 200, "resmsg": data})

    def retrieve(self, request, *args, **kwargs):
        # instance = self.get_object()
        # serializer = self.get_serializer(instance)
        pk = int(kwargs.get("pk"))
        data = settings.CACHES.keys()
        if not pk < len(data):
            raise serializers.ValidationError({"pk": "索引无效"})
        # 数据载体
        sess = {}
        # 返回 key
        r = REDIS.redis_key_scan(list(data)[pk])
        for i in r:
            x = REDIS.redis_key_type(list(data)[pk], i)
            if x == "string":
                sess[i] = REDIS.redis_key_get(list(data)[pk], i)
            elif x == "list":
                sess[i] = REDIS.redis_list_list(list(data)[pk], i)
            elif x == "set":
                sess[i] = REDIS.redis_sset_list(list(data)[pk], i)
            elif x == "zset":
                sess[i] = REDIS.redis_zset_list(list(data)[pk], i)
            elif x == "hash":
                sess[i] = REDIS.redis_hash_list(list(data)[pk], i)
            else:
                print(x is None)
        return Response({"rescode": 200, "resmsg": sess})

    def update(self, request, *args, **kwargs):
        pk = int(kwargs.get("pk"))
        data = settings.CACHES.keys()
        if not pk < len(data):
            raise serializers.ValidationError({"pk": "索引无效"})

        from django_redis import get_redis_connection

        rds = get_redis_connection(data[pk])
        d = []
        while True:
            r = rds.scan(cur)
            cur = r[0]
            d += r[1]
            if r[0] == 0:
                break
        for k in d:
            rds.delete(k)

        return Response({"rescode": 200, "resmsg": "OK"})


class MainVersionListViewSet(viewsets.ModelViewSet):
    __title__ = "场所端版本号"
    __group__ = "后台配置"
    __info__ = {
        "get": "查询场所端版本号列表",
        "post": "创建场所端版本号",
        "put": "编辑场所端版本号",
        "delete": "移除场所端版本号",
    }
    __doc__ = """	list:
    <h4>场所端版本号列表</h4>
    retrieve:
    <h4>场所端版本号详情</h4>
    create:
    <h4>创建场所端版本号</h4>
    update:
    <h4>编辑场所端版本号</h4>
    """
    http_method_names = ["get", "post", "put"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = MainVersionListSerializer
    queryset = MainVersionList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        data = serializer.data.copy()
        pid = data.pop("pid")
        r, faq = MainVersionList.objects.update_or_create(defaults=data, pid=pid)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class TestCreateWorkItemsViewSet(viewsets.ModelViewSet):
    __title__ = "测试创建工作项事务"
    __group__ = "后台配置"
    __info__ = {"post": "测试创建工作项事务"}
    __doc__ = """
    create:\n
    <h4>创建场所端版本号</h4>
    """
    http_method_names = ["post"]
    # authentication_classes = []
    # permission_classes = [AllPermissions]
    authentication_classes = [] if settings.DEBUG else [MyJWTAuthentication]
    permission_classes = [AllPermissions] if settings.DEBUG else [MyPermissions]
    serializer_class = TestCreateWorkItemsSerializer
    queryset = AllinpayPlaceworkitemModel.objects.all()

    # filter_backends = [ListDjangoFilterBackend]
    # filterset_fields = ["pid"]

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        from PlaceManager.tasks import CheckWorkItemModel

        # r = CheckWorkItemModel(**serializer.data)
        r = CheckWorkItemModel.apply_async(kwargs=serializer.data).task_id
        return Response(r)


class GamoPlacetokenListViewSet(viewsets.ModelViewSet):
    __title__ = "注册三方授权"
    __group__ = "后台配置"
    __info__ = {"post": "创建三方授权账户"}
    __doc__ = """
    create:
    <h4>创建三方授权账户</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = GamoPlacetokenListSerializer
    queryset = GamoPlacetokenList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        from iClouds.apidev import has_PassWordB
        from django.db import transaction
        from datetime import datetime, timedelta

        with transaction.atomic():
            r = GamoPlacetokenList(
                status=0,
                name=serializer.data.get("name"),
                appid=has_PassWordB(8, 1),
                secret=has_PassWordB(16, 2),
                created=timezone.now(),
                outdate=timezone.now().date() + timedelta(days=3),
            )
            r.save()
        return Response({"rescode": 200, "resmsg": self.get_serializer(r).data})


class GamoPlacetokenLoginViewSet(viewsets.ModelViewSet):
    __title__ = "登录三方授权"
    __group__ = "后台配置"
    __info__ = {"post": "登录三方授权账户"}
    __doc__ = """
    create:
    <h4>登录三方授权账户</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GamoPlacetokenLoginSerializer
    queryset = GamoPlacetokenList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        from iClouds.apidev import RC4
        import base64

        try:
            r = GamoPlacetokenList.objects.get(
                appid=serializer.data["appid"],
                secret=serializer.data["secret"],
                status=1,
                outdate__gt=timezone.now(),
            )
        except BaseException as err:
            raise serializers.ValidationError(f"登录失败 {err}")
        else:
            x = f"{r.id}-{r.appid}-{r.secret}-{r.outdate}-{timezone.now()}"
            encrypt_func, decrypt_func = RC4()
            encrypted_data = encrypt_func(x.encode("utf-8"))
            r.lasted = base64.b64encode(encrypted_data).decode(encoding="utf-8")
            r.save()
        return Response(
            {
                "rescode": 200,
                "resmsg": {
                    "name": r.name,
                    "token": {"AUTHORIZATION": f"Rearer {r.lasted}"},
                },
            }
        )


class GamoPlacetokenEditViewSet(viewsets.ModelViewSet):
    __title__ = "三方授权接口视图"
    __group__ = "后台配置"
    __info__ = {
        "get": "查询三方授权列表",
        "post": "创建三方授权账户",
        "put": "编辑三方授权",
        "patch": "编辑三方授权",
        "delete": "移除三方授权",
    }
    __doc__ = """	
    list:
    <h4>查询三方授权列表</h4>
    create:
    <h4>创建三方授权账户</h4>
        该接口停用
    retrieve:
    <h4>查询三方授权详情</h4>
    update:
    <h4>编辑三方授权</h4> 
        pu   
    partial_update:
    <h4>编辑三方授权</h4>
        pa
    delete:
    <h4>移除三方授权</h4>"""
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = GamoPlacetokenListSerializer
    queryset = GamoPlacetokenList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["status"]

    # search_fields = ['phone','email']
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        # print(request.data)
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # print(request.data)
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayAuthViewsSerializerViewSet(viewsets.ModelViewSet):
    __title__ = "视图列表(操作权限)"
    __group__ = "公共接口"
    __info__ = {"get": "查询视图列表"}
    __doc__ = """	
    list:
    <h4>查询视图列表</h4>
        staff = int 视图类型
            1 云端视图(权限)
            2 员工视图(权限)
            4 未启用
            8 未启用
    retrieve:
    <h4>查询视图详情</h4>"""
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayAuthViewsSerializer
    queryset = AllinpayAuthViews.objects.all()

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    filterset_class = AllinpayAuthViewsFilterSet
    # filterset_fields = ['gender', 'status']
    search_fields = ["name", "info", "group"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


# 检查视图
filter_views(globals())
